//
//  YYSpreadSheetTableViewCell.swift
//  表格行
//
//  Created by yao_yu on 15/6/30.
//  Copyright © 2015年 yao_yu. All rights reserved.
//

import UIKit

protocol YYSpreadSheetTableViewCellDelegate {
    
}

class YYSpreadSheetTableViewCell: UITableViewCell {
    
    private var cells = [UILabel]()
    private let viewBottomLine = CAShapeLayer()
    
    var margin:CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    var cellSpace:CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    var cellFontSize:CGFloat = 14 {
        didSet {
            for cell in cells {
                cell.font = UIFont(name: cell.font.fontName, size: cellFontSize)
            }
        }
    }
    
    var cellDefines:[(name:String, width:CGFloat)] = [] {
        didSet {
            removeExtraLabels()
            addExtraLabels()
            updateCellFrames()
        }
    }
    
    var rowData:[String:String]? {
        didSet {
            if let _rowData = rowData {
                assert(cellCount > 0, "单元格未定义, 在设置数据前需要设置cellDefines变量")
                for (i, item) in cellDefines.enumerate() {
                    if let cellString = _rowData[item.name] {
                        cells[i].text = cellString
                    }
                }
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupView()
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }
    
    private func setupView() {
        contentView.backgroundColor = UIColor.clearColor()
        viewBottomLine.fillColor = UIColor.darkGrayColor().CGColor
        viewBottomLine.strokeColor = nil
        contentView.layer.addSublayer(viewBottomLine)
    }
    
    override func layoutSubviews() {
        updateBottomLine()
        updateCellFrames()
    }
    
    private func updateBottomLine() {
        let lineHeight:CGFloat = 0.1
        let rect = CGRectMake(0, contentView.bounds.height - lineHeight, contentView.bounds.width, lineHeight)
        viewBottomLine.path = UIBezierPath(rect: CGRect(origin: CGPointZero, size: rect.size)).CGPath
        viewBottomLine.frame = rect
    }
    
    private func updateCellFrames() {
        if cellCount <= 0 || totalWidth <= 0 {
            return
        }
        
        let cellHeight = self.cellHeight
        var x:CGFloat = margin
        let y:CGFloat = (contentView.bounds.height - cellHeight) / 2
        for (i, cellWidth) in cellWidths.enumerate() {
            cells[i].frame = CGRectMake(x, y, cellWidth - cellSpace, cellHeight)
            x += cellWidth
        }
    }
    
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    
}

//界面布局
extension YYSpreadSheetTableViewCell {
    private func removeExtraLabels() {
        if cellCount > cellDefines.count {
            let aRange = cellDefines.count ..< cellCount
            for i in aRange {
                cells[i].removeFromSuperview()
            }
            cells[aRange] = []
        }
    }
    
    private func addExtraLabels() {
        if cellCount < cellDefines.count {
            for _ in cellCount..<cellDefines.count {
                let aLabel = UILabel(frame: CGRectZero)
                aLabel.textAlignment = NSTextAlignment.Center
                aLabel.font = UIFont.systemFontOfSize (cellFontSize)
                cells.append(aLabel)
                contentView.addSubview(aLabel)
            }
        }
    }
}

//扩展查询
extension YYSpreadSheetTableViewCell {
    private var cellCount: Int {
        return cells.count
    }
    
    private var cellDefineTotalWidths:CGFloat {
        return cellDefines.map {$0.1}.sum()
    }
    
    private var totalWidth:CGFloat {
        return contentView.bounds.width
    }
    
    private var cellHeight:CGFloat {
        return contentView.bounds.height
    }
    
    private var cellWidthRatios:[CGFloat] {
        let total:CGFloat = cellDefineTotalWidths
        return cellDefines.map({ (item:(name:String, width:CGFloat)) -> CGFloat in
            return item.width / total
        })
    }
    
    private var cellWidths:[CGFloat] {
        let unitWidth:CGFloat = (totalWidth - margin - margin + cellSpace) / cellDefineTotalWidths
        return cellDefines.map({ (item:(name:String, width:CGFloat)) -> CGFloat in
            return item.width * unitWidth
        })
    }
}
